<template>
  <div class="red-book-form">
    <a-form layout="vertical">
      <a-form-item label="标题" v-bind="validateInfos.title" style="margin-bottom: 0;">
        <a-radio-group v-model:value="formRef.titleType">
          <a-radio :value="1">单标题</a-radio>
          <a-radio :value="2">多标题</a-radio>
        </a-radio-group>
        <a-input :value="formRef.title" @input="inputChange1($event,index)" class="my-10" v-if="formRef.titleType == 1"
          placeholder="请输入标题">
          <template #suffix>
            {{ getStringLength(formRef.title) }}/30
          </template>
        </a-input>
        <template v-for="(item, index) in formRef.sub_title" :key="index">
          <a-input class="my-10" :value="formRef.sub_title[index]" @input="inputChange($event,index)"
            v-if="formRef.titleType == 2 && index == 0" placeholder="请输入标题">
            <template #suffix>
              {{ getStringLength(item) }}/30
            </template>
          </a-input>
        </template>
      </a-form-item>
      <template v-if="formRef.titleType == 2">
        <a-form-item v-bind="validateInfos.sub_title">
          <template v-for="(item, index) in formRef.sub_title" :key="index">
            <a-input class="my-10" :value="formRef.sub_title[index]"  @input="inputChange($event,index)" v-if="index > 0"
              placeholder="请输入标题">
              <template #suffix>
                {{ getStringLength(item) }}/30
              </template>
            </a-input>
          </template>

        </a-form-item>
      </template>


      <a-form-item label="封面" v-bind="validateInfos.cover_img" style="margin-top: 24px;">
       
        <a-radio-group v-model:value="formRef.cover_type" @change="coverTypeChange" style="margin-bottom: 10px;">
          <a-radio :value="2">单图</a-radio>
          <a-radio :value="3">三图</a-radio>
          <a-radio :value="1">无封面</a-radio>
        </a-radio-group>
      
          <a-upload  v-if="formRef.cover_type!=1" :key="index" :action="$utils.imgAction" :headers="{ 'org-token': $store.getters.token }"
          v-model:file-list="imgInfoList" @change="handleLogoUpload" @preview="handlePreview" :multiple="coverArr.length > 1"
          name="image" :data="{ dir: 'work_ai' }" accept="image/*" list-type="picture-card">
          <div v-if="!formRef.cover_img.length || imgInfoList.length< coverArr.length">
            <PlusOutlined />
            <div>上传封面</div>
          </div>
        </a-upload>
      
      </a-form-item>
     
      
      <a-form-item label="发布时间" required>
            <a-radio-group v-model:value="formRef.publishType">
              <a-radio :value="1">立即发布</a-radio>
              <a-radio :value="2">定时发布</a-radio>
           </a-radio-group>
          </a-form-item>
          <a-form-item  v-if="formRef.publishType==2"  v-bind="validateInfos.fix_at">
              <a-date-picker :disabledDate="disabledDate"  :disabled-time="disabledDateTime" :show-time="{ format:'YYYY-MM-DD HH:mm' }" format="YYYY-MM-DD HH:mm" placeholder="请选择时间" @change="onTimeChange" />
          </a-form-item>
    </a-form>
    <a-modal :visible="previewVisible" :footer="null" @cancel="() => previewVisible = false">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
   
<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watchPostEffect,
  ref,
} from "vue";
import { useVModel } from '@vueuse/core'
import request from "../../../common/utils/request"
import { useRoute, useRouter } from "vue-router";
import moment from 'moment'
import { Modal, notification, message, Form } from "ant-design-vue";
import { CloseOutlined, SyncOutlined, PlusOutlined } from "@ant-design/icons-vue";
import _ from 'lodash'
import utils from "@/common/utils/utils"
import { useDebounceFn } from '@vueuse/core'
import { watch,nextTick,onMounted,watchEffect } from "vue";

let qrCodeTimer = null;
export default defineComponent({
  name: "toutiao",
  components: { CloseOutlined, SyncOutlined, PlusOutlined },
  formData: {
    titleType: 1,
    title: '',
    sub_title: ['', '', '', '', '',],
    cover_img: [],
    cover_type:1,//封面类型 1-无封面 2-单图 3-三图
    publishType:1,
    fix_at: null,
   
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
      default: () => null
    },
    title: {
      type: String,
      default: '',
    },
    accountId: {
      type: [Number, String],
      default: ''
    },
    content: {
        type: String,
        default: ''
      },
  },

  setup(props, context) {
    const state = reactive({
      previewImage: '',
      previewVisible: false,
      publishTime: '',
      group_account_List: [],
      topicList: [],
      selectTopicList: [],
      totalTopicList: [],
      isRequired: false,
    });
    
    const formRef = useVModel(props, 'formData', context.emit)

    const useForm = Form.useForm;


    let imgInfoList = ref([])
    let validate_cover_img = async (_rule, value) => {
      console.log('value',value);
        if(formRef.value.cover_type==2&& imgInfoList.value.length == 0){
          return Promise.reject('请上传封面');
        }else if(formRef.value.cover_type==3&& imgInfoList.value.length == 0){
          return Promise.reject('请上传封面');
        }else if(formRef.value.cover_type==3&& imgInfoList.value.length>=1&& imgInfoList.value.length<3){
          return Promise.reject('请上传3张封面');
        }
        return Promise.resolve();
    }
    let validate_time = () => {

      if (formRef.value.publishType == 2 && !formRef.value.fix_at) {

        return Promise.reject('请选择发布时间');
      } else {
        return Promise.resolve();
      }
    }
    let validate_title = () => {
      if (formRef.value.titleType == 1) {//单标题

        if (formRef.value.title.length == 0) {
          console.log(formRef.value.title.length);
          return Promise.reject('请填写标题');
        } else {
          return Promise.resolve();
        }

      } else {
        if (formRef.value.sub_title[0].length == 0) {
          return Promise.reject('请填写标题');
        } else {
          return Promise.resolve();
        }

      }
    }

    const onTimeChange = (e) => {

      formRef.value.fix_at = e ? moment(e).format('YYYY-MM-DD HH:mm') : null
    }

    // 封面数组
    const coverArr = computed(()=>{
      let arr = []
      let arrLength =  formRef.value.cover_type==1?0:formRef.value.cover_type==2?1:3
      arr = Array.from({ length:4}, (_, index) => index).splice(1, arrLength)
      return arr
    })
    const handleLogoUpload = (info) => {

      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList.map((file, index) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
            } else {
              message.warning(file.response.msg);
              resFileList.splice(index, 1);
            }
          }
        });
      }

      imgInfoList.value = resFileList;
      formRef.value.cover_img = resFileList.map(item => {
        return item.url
      })


    }

  
    watch(() => formRef.value.sub_title[0], (val) => {
      validate(['title'])
    })
    watch(() => formRef.value.titleType, (val) => {
      validate(['title'])
    })

    const rulesRef = reactive({
      title: [
        { required: true, message: '标题为必填项', validator: validate_title, },
      ],
      cover_img: [
        {
          required: true,
          validator: validate_cover_img,
          trigger: 'change',
        }
      ],
      fix_at: [
        {
          validator: validate_time,
          trigger: 'change',
        }
      ],
    })

    const { resetFields, validate, validateInfos } = useForm(formRef, rulesRef)
    watch(() => props.title, (newTitle, oldTitle) => {
      if (!formRef.value.title || formRef.value.title == oldTitle) {
        formRef.value.title = props.title
      }
    },
      { immediate: true })
   
    const disabledDate = (current) => {
      // 时间组件当前日期之前的日期不能选择
      return current && current < moment().startOf('day')
    }
    const disabledDateTime = (choosTime) => {
      let currentHour = moment().hour()
      let currentMinute = moment().minute()
    
      let disabledMinutes =  () => []
      let disabledHours = ()=>[]
      if(choosTime){
        disabledMinutes = moment(choosTime)>moment()?
       () => []:
       () => Array.from({ length: 61 }, (_, index) => index).splice(0, currentMinute + 1)

       disabledHours = moment(choosTime)>moment()?() => []:
       () => Array.from({ length: 25 }, (_, index) => index).splice(0, currentHour)
      }

      return {
        disabledHours,
        disabledMinutes,

      };
    }
    const handlePreview = async (file) => {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      state.previewImage = file.url || file.preview;
      state.previewVisible = true;
    }
    const getBase64 = (file) => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
      });
    }

    /**
* 计算字符串的长度
* @param {string} str 要计算长度的字符串
* @returns {number} 字符串的长度
*/
    function getStringLength(str) {
      let len = 0;
      for (let i = 0; i < str.length; i++) {
        const code = str.charCodeAt(i);
        if (isChineseCharacter(code)) {
          len++;
        } else {
          len += 0.5;
        }
      }
      return len
    }

    /**
     * 判断字符是否为中文字符
     * @param {number} charCode 字符的 Unicode 编码
     * @returns {boolean} 是否为中文字符
     */
    function isChineseCharacter(charCode) {
      return charCode >= 0x4E00 && charCode <= 0x9FA5;
    }
    const inputChange = (e,index)=>{
      let txt = e.target.value;
        if(getStringLength(txt)<=30){
          formRef.value.sub_title[index]=txt
        }
     
    }
    const inputChange1 = (e,index)=>{
      let txt = e.target.value;
        if(getStringLength(txt)<=30){
          formRef.value.title=txt
        }
    }
   
    const coverTypeChange = ()=>{
      imgInfoList.value=[]
      formRef.value.cover_img = []
      validate(['cover_img'])
    }
   
 
   
    watch(()=>props.content,()=>{
      let {images}  = utils.parseRichText(props.content)
      if( formRef.value.cover_img.length==0){
          formRef.value.cover_img = images
          imgInfoList.value = images.map((item,index)=>{
          return {
            uid: index,
            name: 'image.png',
            status: 'done',
            url: item,
          }
        })
        if (images.length == 1) {
          formRef.value.cover_type = 2
        } else if (images.length >= 2) {
          formRef.value.cover_type = 3
        } else {
          formRef.value.cover_type = 1
        }
      }
   
   },{deep:true,immediate:true})

    
    return {
      ...toRefs(state),
      onTimeChange,
      formRef,
      handleLogoUpload,
      imgInfoList,
      rulesRef,
      validate,
      validateInfos,
      disabledDate,
      disabledDateTime,
      handlePreview,
      getStringLength,
      inputChange,
      inputChange1,
      coverArr,
      coverTypeChange,
    };
  },
});
</script>
   
<style lang="less" scoped>
:deep(.ss-row) {
  flex-wrap: unset;
}

:deep(.ss-form-item-has-error .ss-upload) {
  background-color: #fff;
  border-color: #ff4d4f;
}
</style>
   